package info.niwota.install.web;

import info.niwota.commons.acl.AccessControl;
import info.niwota.commons.web.AjaxObject;
import info.niwota.install.Debug;
import info.niwota.install.Installer;

import org.json.JSONObject;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class InstallObject extends AjaxObject {

	public static final String NAME = "installer";

	private static final String TAG = "InstallObject";

	public InstallObject(Context ctx) {
		super(ctx);
	}

	public Object install(JSONObject param, Uri uri) throws Exception {
		if (Debug.DEBUG) {
			Log.d(TAG, "install param: " + param + " uri: " + uri);
		}
		String label = Label.LABEL;
		String group = uri.getQueryParameter("group");
		String user = uri.getQueryParameter("user");

		int g = (TextUtils.isEmpty(group) ? AccessControl.ACCESS_PUBLIC
				: Integer.parseInt(group));

		JSONObject jo = new JSONObject();

		//
		if (!canAccess(g, user, label)) {
			//throw new Exception("Accessed denied");
			jo.put("rc", false);
			jo.put("error", "Accessed denied");
			return jo;
		}
		
		try {
			//boolean remove = toBoolean(uri.getQueryParameter("remove"));
			String apk = uri.getQueryParameter("apk.path");
			
			if (Debug.DEBUG) {
				Log.d(TAG, "apk: "+ apk);
			}
			//
			Installer.install(ctx, apk);
			//
			jo.put("rc", true);
			jo.put("success", "APK uploaded");
			
		} catch (Exception e) {
			jo.put("rc", false);
			jo.put("error", "Failed to install: " + e.getMessage());
		}

		return jo;
	}

	protected int toInt(String s, int def) {
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
		}
		return def;
	}
	
	protected boolean toBoolean(String s) {
		try {
			return Boolean.parseBoolean(s);
		} catch (Exception e) {
		}
		return false;
	}

	protected boolean isLocal(Uri uri) {
		String peer = uri.getQueryParameter("peer");
		String jid = uri.getQueryParameter("jid");
		return TextUtils.isEmpty(peer) || peer.equals(jid);
	}
}
